package com.planet.merchant.service.impl;

/**
 * @author: ggm
 * @data 2025年03月31日 21:32
 */
import com.planet.merchant.domain.FileInfo;
import com.planet.merchant.mapper.FileInfoMapper;
import com.planet.merchant.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileServiceImpl implements IFileService {
    private final FileInfoMapper fileInfoMapper;

    @Autowired
    public FileServiceImpl(FileInfoMapper fileInfoMapper) {
        this.fileInfoMapper = fileInfoMapper;
    }

    public String uploadFile(MultipartFile file) throws IOException {
        // 定义文件存储路径
        String uploadDir = "D:\\upload\\springboot";
        Path uploadPath = Paths.get(uploadDir);

        // 如果目录不存在，则创建
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 保存文件
        String fileName = file.getOriginalFilename();
        String newName = UUID.randomUUID() + fileName.substring(fileName.indexOf("."));
        Path filePath = uploadPath.resolve(newName);
        Files.copy(file.getInputStream(), filePath);

        // 构建文件URL
        String fileUrl = uploadDir + newName;

        // 保存文件URL到数据库
        FileInfo fileInfo = new FileInfo();
        fileInfo.setUrl(fileUrl);
        fileInfoMapper.insertFileInfo(fileInfo);

        return fileUrl;
    }
}

